import React, { useState, useEffect } from "react";
import { Button } from "antd";

const CountdownButton = ({timeout=60, onClick}) => {
  const [countdown, setCountdown] = useState(0); // 倒计时的秒数
  const [isDisabled, setIsDisabled] = useState(false); // 按钮禁用状态

  useEffect(() => {
    let timer;
    if (countdown > 0) {
      // 开始倒计时
      timer = setTimeout(() => {
        setCountdown((prev) => prev - 1);
      }, 1000);
    } else if (countdown === 0) {
      // 倒计时结束，恢复按钮可点击状态
      setIsDisabled(false);
    }
    return () => clearTimeout(timer); // 清理定时器
  }, [countdown]);

  const handleClick = () => {
    if(typeof onClick === 'function'){
      onClick(startCount);
    } else {
      startCount();
    }
  };

  const startCount = ()=>{
    setIsDisabled(true); // 按钮禁用
    setCountdown(timeout); // 设置倒计时初始值
  }

  return (
    <Button
      type="default"
      onClick={handleClick}
      disabled={isDisabled} // 根据状态禁用按钮
      style={{ width: "100%" }}
    >
      {isDisabled ? `${countdown} 秒` : "获取验证码"}
    </Button>
  );
};

export default CountdownButton;
